package se.combitech.combiorder.service;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import se.combitech.combiorder.model.Address;
import se.combitech.combiorder.model.Customer;
import se.combitech.combiorder.model.Order;

/**
 * Session Bean implementation class CustomerService
 */
@Stateless
public class CustomerService {

    @Inject
    private Logger log;

    @Inject
    private EntityManager em;

    @Inject
    private Event<Customer> customerEventSrc;

    public void save(Customer customer) throws Exception {
        log.info("Sparar " + customer.getFirstName() + " " + customer.getLastName());
        em.persist(customer);
        customerEventSrc.fire(customer);
    }

    public void change(Customer customer) throws Exception {
        log.info("Sparar " + customer.getFirstName() + " " + customer.getLastName());
        em.merge(customer);
        customerEventSrc.fire(customer);
    }

    public void delete(Customer customer) throws Exception {
        log.info("Tar bort " + customer.getFirstName() + " " + customer.getLastName());
        Customer attachedCustomer = em.merge(customer);
        em.remove(attachedCustomer);
        customerEventSrc.fire(customer);
    }

    @SuppressWarnings("unchecked")
    public List<Customer> findAllCustomers() {
        return em.createQuery("select c from Customer c order by c.lastName").getResultList();
    }

    public Customer findCustomerByID(long id) {
        return em.find(Customer.class, id);
    }

}
